#include "array.h"
#include "sparse.h"
#include "parser.h"
#include <fstream> 
#include <sstream>
#include <string>
#include <utility>
using std::ifstream;
using std::string;
using std::stringstream;
using std::pair;

parser::parser(const char* file){
    longest=0;
    input.open(file);
}

int parser::parseExample(int& label, Array<int>& ai, Array<real>& av){
    string line;
    unsigned int ind;
    real val;
    char colon;
    ai.clear();
    av.clear();
    do{
        if(!getline(input,line))
            return 0;
        ind = line.find_first_of("#");
        if(ind!=string::npos)
            line.erase(ind);
        ind = line.find_first_not_of(" \t");
    }while(ind==string::npos);
    line.erase(0,ind);
    stringstream s(line);
    s>>label;
    while(s>>ind && s>>colon && s>>val){
        if(ind>longest)
            longest=ind;
        ai.push(ind);
        av.push(val);
    }
    return 1;
}

void parser::parse(Array<vector*>& examples){
    Array<int> ai;
    Array<real> av;
    int l;
    examples.clear();
    vector* v;
    while(parseExample(l, ai, av)){
        v = new vector(l,ai,av);
        examples.push(v);
    }
}

int parser::getdim(){
    return longest;
}

parser::~parser(){
    input.close();
}
